<?php
declare (strict_types = 1);

namespace app\api\middleware;
use app\api\common\JwtAuth;
use liliuwei\think\Jump;
use think\Response;


class Auth
{
    use Jump;

    private static $controller = ['login', 'loginOut'];

    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next) :Response
    {
        //获取不到控制器 有需要可以自行修改
        $controller = explode('/', $request->url())[3] ?? '';
        if (in_array($controller, self::$controller)) {
            return $next($request);
        }

        $token = $request->header('token');

        if ($token) {
            if (count(explode('.', $token)) !== 3) {
                $this->error('错误的token身份信息，请重新登录', '');
            }

            $jwtAuth = JwtAuth::getInstance();

            $jwtAuth->setToken($token);


            if (!$jwtAuth->validationToken()) {
                return $next($request);
            } else {
                $this->error('登录身份已过期');
            }

        } else {
            $this->error('请先登录');
        }

        return $next($request);

    }
}
